package com.aitangbao.web.quartz;

import com.aitangbao.common.toolkit.Constant;
import com.aitangbao.core.mapper.KJobDao;
import com.aitangbao.core.mapper.KTransDao;
import com.aitangbao.core.model.KJob;
import com.aitangbao.core.model.KTrans;
import com.aitangbao.web.utils.SpringContextUtil;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;

public class QuartzListener implements JobListener{

	@Override
	public String getName() {
		return System.currentTimeMillis() + "QuartzListener";
	}
	@Override
	public void jobToBeExecuted(JobExecutionContext context) {
	}
	@Override
	public void jobExecutionVetoed(JobExecutionContext context) {
	}
	@Override
	public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
		KJobDao kJobDao = (KJobDao) SpringContextUtil.getBean("KJobDao");
		KTransDao kTransDao = (KTransDao) SpringContextUtil.getBean("KTransDao");
		String jobName = context.getJobDetail().getKey().getName();
		String jobGroupName = context.getJobDetail().getKey().getGroup();
		String triggerName = context.getTrigger().getKey().getName();
		String triggerGroupName = context.getTrigger().getKey().getGroup();
		//一次性任务，执行完之后需要移除
		QuartzManager.removeJob(jobName, jobGroupName, triggerName, triggerGroupName);

		JobDataMap dataMap = context.getJobDetail().getJobDataMap();
		String jobId = String.valueOf(dataMap.get(Constant.TRANSID));
		String jobtype = String.valueOf(dataMap.get(Constant.JOBTYPE));
		if (jobtype.equals("1")){
			KJob kJob = kJobDao.selectById(Integer.valueOf(jobId));
			kJob.setJobStatus(2);
			kJobDao.updateById(kJob);
		}
		else if (jobtype.equals("2")) {
			KTrans kTrans = kTransDao.selectById(Integer.valueOf(jobId));
			kTrans.setTransStatus(2);
			kTransDao.updateById(kTrans);
		}
	}
}
